package com.yc.c118s3qnzf.service.impl;

import com.google.gson.Gson;
import com.yc.c118s3qnzf.entity.Type;
import com.yc.c118s3qnzf.mapper.TypeMapper;
import com.yc.c118s3qnzf.service.ITypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author baomidou
 * @since 2022-11-28
 */
@Service
public class TypeServiceImpl extends ServiceImpl<TypeMapper, Type> implements ITypeService {

    //基于对字符串类型数据操作的模板
    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Override
    public List<Type> queryAll() {
        //设计键值QnzfTypes
        Boolean has = stringRedisTemplate.hasKey("QnzfTypes");
        if(has) {
            System.out.println("Redis 缓存数据。。。");
            //获取redis 中的type list集合
            List<String> qnzfTypes = stringRedisTemplate.opsForList().range("QnzfType",0,-1);
            //将list 中的json 转成Type
            List<Type> list = qnzfTypes.stream().map(json->{
                Type type = new Gson().fromJson(json, Type.class);
                return type;
            }).collect(Collectors.toList());
            return list;
        }else {
            List<Type> list = this.list();
            //将查询结果缓存
            for (Type type : list){
                String json = new Gson().toJson(type);
                stringRedisTemplate.opsForList().rightPush("QnzfTypes",json);
            }
            return list;
        }
    }

    public boolean save(Type entity){
        stringRedisTemplate.delete("QnzfTypes");
        return super.save(entity);
    }
}
